﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>跨域测试</title>
</head>
<body>
    <p>
        <input id="btnTest" type="button" value="浏览器跨域单元测试" onclick="init();" /></p>
</body>
</html>
<script type="text/javascript">
    var ContextPath = window.location.protocol + "//" + window.location.host +
        (window.location.pathname.lastIndexOf("/") > 0 ? (window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/") + 1)) : "/");

    function init(urlprex) {
        //alert(ContextPath);
        var iframeProxy = getIframe();
        if(!iframeProxy)
            iframeProxy = document.createElement('iframe');
        
        var state = 0;
        var loadfn = function () {
            if (state === 1) {
                var data = iframeProxy.contentWindow.name; // 读取数据
                alert(data); //弹出返回值
                if (iframeProxy.detachEvent) {//判断是否是IE
                    iframeProxy.detachEvent('onload', loadfn);
                }
            } else if (state === 0) {
                state = 1;
                iframeProxy.contentWindow.location = ContextPath + "proxy.html"; // 设置的代理文件
            }
        };

        iframeProxy.src = ContextPath + 'othersite/check.html';
        iframeProxy.style.display = "none";//隐藏窗口

        if (iframeProxy.attachEvent) {//判断是否为IE
            iframeProxy.attachEvent('onload', loadfn);
        } else {
            iframeProxy.onload = loadfn;
        }
        document.body.appendChild(iframeProxy);
    }

    function getIframe(contentWindow) {
        var iframes = document.getElementsByTagName("iframe"),
        ileng = iframes.length;
        if (ileng > 0)
            return iframes[0];
        //for (var i = 0; i < ileng; i++) if (iframes[i].contentWindow == contentWindow) return iframes[i];
    }
//    function destory() {
//        if (iframeProxy) {
//            iframeProxy.contentWindow.document.write('');
//            iframeProxy.contentWindow.close();
//            document.body.removeChild(iframeProxy);
//        }
//    }
</script>
